package com.open.capacity.study.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Stage;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.study.dao.StageDao;
import com.open.capacity.study.service.StageService;
import com.open.capacity.study.utils.GenerateCodeUtil;
import com.open.capacity.study.utils.MyDownLoadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class StageServiceImpl implements StageService {
    @Autowired
    private StageDao stageDao;

    /**
     * 新增
     * @param stage
     * @return
     * @throws ServiceException
     */
    @Override
    public Result insert(Stage stage) throws ServiceException {
        try {
            //获取体系id
            Integer tsysId = stage.getTsysId();
            //统计该体系下目前有多少阶段
            int count = stageDao.count(tsysId);
            //生成编号
            String stcode = GenerateCodeUtil.generateCode("ts",tsysId,count);
            stage.setStcode(stcode);
            int res = stageDao.insert(stage);
            stage.setCretim(new Date());
            log.info("新增学习阶段：{}",stage);
            return res > 0 ? Result.succeed(stage,"新增成功"):Result.failed("新增失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public Result updateStatus(Map<String, Object> params) throws ServiceException{
        try {
            String code = MapUtils.getString(params,"stcode");
            int status = MapUtils.getIntValue(params,"status");
            Stage stage = stageDao.findByCode(code);
            if (stage == null){
                return Result.failed("不存在该阶段");
            }
            stage.setStatus(status);
            stage.setUpdtim(new Date());
            int res = stageDao.updateStatusByCode(stage);
            log.info("修改教学体系：{}",stage);
            return res>0 ? Result.succeed(stage,"修改成功") : Result.failed("修改失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    @Transactional
    public Result update(Stage stage) throws ServiceException {
        try {
            Stage updateStage = stageDao.findByCode(stage.getStcode());
            //根据code查询阶段名，并判断阶段名是否要修改
            if (!stage.getStitle().equals(updateStage.getStitle())){
                Stage stage1 = stageDao.findByTitle(stage);
                //根据阶段名判断体系是否存在
                if (stage1 != null){
                    return Result.failed("该阶段名已被使用，请重新输入");
                }
            }
            int res = stageDao.updateByCode(stage);
            stage.setUpdtim(new Date());
            log.info("修改教学体系：{}",stage);
            return res>0 ? Result.succeed(stage,"修改成功") : Result.failed("修改失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public PageResult<Stage> findStage(Map<String, Object> params) throws ServiceException {
        try {
            int total = stageDao.total(params);
            List<Stage> stageList = Collections.emptyList();
            if (total > 0){
                PageUtil.pageParamConver(params, false);
                stageList = stageDao.findList(params);
            }
            //收集所有数据
            return PageResult.<Stage>builder().data(stageList).code(0).count((long) total).build();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 下载验收标准
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public Result download(Map<String, Object> params) throws ServiceException {
        try {
            PageResult<Stage> stage = findStage(params);
            List<Stage> data = stage.getData();
            if (MyDownLoadUtil.load(data.get(0))) {
                return Result.succeed("下载成功");
            }
            else
                return Result.failed("下载失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }
}
